var express = require('express')
var router = express.Router()
// 文件管理和下载
var fs = require('fs')
var request = require('request')

/**
 * @function 执行下载文件操作
 * @param {String} uri 要下载的网址
 * @param {String} filename 下载后的存储名
 * @param {Function} callback 下载后执行回调
 */
function downloadFile(uri,filename,callback){
  var stream = fs.createWriteStream(filename)
  request(uri).pipe(stream).on('close', callback) 
}
/**
 * 
 * @param {String} filename 要生成api.js的文件名 
 */
function generateApi (ip) {
  return new Promise ((resolve, reject) => {
    let filename = `../json/${ip.replace(/\./g, '')}.json`
    var jsonData = require(filename)
    let arr = []
    for (let i in jsonData.paths) {
      try {
        arr.push({
          name: `${jsonData.paths[i]['post'].operationId}`,
          url: `${i}`,
          remark: `${jsonData.paths[i]['post'].summary}`
        })
        // txt += `${jsonData.paths[i]['post'].operationId}: '${i}', // ${jsonData.paths[i]['post'].summary}\r\n `
      } catch (e) {
        arr.push({
          name: `${jsonData.paths[i]['get'].operationId}`,
          url: `${i}`,
          remark: `${jsonData.paths[i]['get'].summary}`
        })
        // txt += `${jsonData.paths[i]['get'].operationId}: '${i}', // ${jsonData.paths[i]['get'].summary}\r\n `
      }
    }
    resolve(arr)
  })
}
/**
 * @function 根据ip和接口名生成searhForm
 */
function generateSearchForm (ip, apiName) {
  return new Promise ((resolve, reject) => {
    let filename = `../json/${ip.replace(/\./g, '')}.json`
    var jsonData = require(filename)
    console.log(apiName)
    let methods = jsonData.paths[apiName].post === undefined ? 'get' : 'post'

      if (jsonData.paths[apiName][methods].parameters[0].schema !== undefined) {
        // 封装了参数
        let name = jsonData.paths[apiName][methods].parameters[0].schema.$ref.replace('#/definitions/', '')
        resolve(jsonData.definitions[name].properties)
      } else {
        // 自带参数
        resolve(jsonData.paths[apiName][methods].parameters)
      }

  })
}
/**
 * @function 根据ip和接口名生成表格
 */
function generateTabelFormat (ip, apiName) {
  return new Promise ((resolve, reject) => {
    try {
      let filename = `../json/${ip.replace(/\./g, '')}.json`
      var jsonData = require(filename)
      let methods = jsonData.paths[apiName].post === undefined ? 'get' : 'post'
      let name = jsonData.paths[apiName][methods].responses[200].schema.$ref.replace('#/definitions/', '')
      resolve(jsonData.definitions[name].properties)
    } catch (e) {
      resolve('0') // 返回的就一个200，没有其他东西了
    }
  })
} 
/**
 * @function 下载json
 */
router.post('/', function(req, res, next) {
  var fileUrl  = `http://${req.body.ip}:8077/swagger/v1/swagger.json` // 接收传进来的ip就可以了
  let filename = `./json/${req.body.ip.replace(/\./g, '')}.json`
  downloadFile(fileUrl,filename,function(){
    // 生成session
    // req.session.ip = `${req.body.ip}`; //每一次访问时，session对象的lastPage会自动的保存或更新内存中的session中去。
    // 提示完成
    res.json({
      state: 200,
      data: {
        ip: `${req.session.ip}`
      },
      msg: `登录成功,获取IP为${req.session.ip}`
    })
  })
})
/**
 * @function 生成api.js
 */
router.post('/apijs', function(req, res, next) {
  generateApi(`${req.body.ip}`).then((response) => {
    res.json({
      state: 200,
      data: {
        record: response
      },
      msg: `获取成功`
    })
  })
})
/**
 * @function 生成searchForm
 */
router.post('/api/searchform', function(req, res, next) {
  generateSearchForm(`${req.body.ip}`, `${req.body.apiName}`).then(response => {
    res.json({
      state: 200,
      data: {
        record: response
      },
      msg: `获取成功`
    })
  })
})
/**
 * @function 生成表格
 */
router.post('/api/table', function(req, res, next) {
  generateTabelFormat(`${req.body.ip}`, `${req.body.apiName}`).then(response => {
    if (response !== '0') {
      res.json({
        state: 200,
        data: {
          record: response
        },
        msg: `获取成功`
      })
    } else {
      res.json({
        state: 500,
        data: {
          record: response
        },
        msg: `无数据`
      })
    }
  })
})
module.exports = router
